package com.kugua.zfms.mq;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerOrderly;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.consumer.ConsumeFromWhere;
import com.alibaba.rocketmq.common.message.MessageExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * TODO 优化Consumer,看一下其他人是如何实现的
 * <p></p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author cuiyh9
 * @version 1.0
 * @Date Created in 2018年11月28日 17:55
 * @since 1.0
 */
@Slf4j
@Component
public class RocketConsumerListener implements ApplicationRunner,DisposableBean {



    private DefaultMQPushConsumer feedContentConsumer;

    private void init() {
        log.info("start---------------:");
        String group  = "zfmsFeedContentConsumer";
        feedContentConsumer = new DefaultMQPushConsumer(group);
        feedContentConsumer.setNamesrvAddr("10.16.37.110:9876");
        feedContentConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        try {
            feedContentConsumer.subscribe(RocketProviderClient.TOPIC_CENSOR_FEED, "*");
            feedContentConsumer.registerMessageListener(new MessageListenerOrderly() {
                @Override
                public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                    try {
                        log.info("22222222222222222222222222222222222222222222:" + list + "," + new String(list.get(0).getBody(), "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    return ConsumeOrderlyStatus.SUCCESS;


                }
            });
            feedContentConsumer.start();
        } catch (MQClientException e) {
            log.error("", e);
        }

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        init();

    }

    @Override
    public void destroy() throws Exception {
        feedContentConsumer.shutdown();
    }
}
